<template>
  <div class="department-container">
    <div class="app-container">
      <div class="company">
        <div class="c-left">{{ companyInfo.name }}</div>
        <div class="c-right">
          <div class="cr-left">负责人</div>
          <div class="cr-right">
            <el-dropdown>
              <span class="el-dropdown-link">
                下拉菜单<i class="el-icon-arrow-down el-icon--right" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="addDepartment('')">添加子部门</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div class="tree">
        <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick">
          <div slot-scope="{data: mydata}" class="company">
            <div class="c-left">{{ mydata.name }}</div>
            <div class="c-right">
              <div class="cr-left">{{ mydata.manager }}</div>
              <!-- 碰到一个复杂的页面结构，第一反应，一定是去找其他人写的组件，要么是element-ui，要么去百度 搜 vue 下拉插件 -->
              <div class="cr-right">
                <!-- 下面代码复制过来 -->
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="addDepartment(mydata)">添加子部门</el-dropdown-item>
                    <el-dropdown-item @click.native="editDepartment(mydata)">编辑部门</el-dropdown-item>
                    <el-dropdown-item v-if="!mydata.children || mydata.children.length === 0" @click.native="deleteDepBtn(mydata)">删除部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
          </div>
        </el-tree>
      </div>
    </div>
    <el-dialog
      v-if="dialogVisible"
      :title="isEdit ? '编辑部门' : '新增部门'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <update-dialog ref="dialogRef" :arr-list-to-child="arrListToChild" :is-edit="isEdit" :current-pid="currentPid" @MyCloseEvent="dialogVisible = false" @success="updateSuccess" />
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentInfoReqest, deleteDeparmentByIdRequest } from '@/api/department'
import { transformListToTree2 } from '@/utils'
import UpdateDialog from './UpdateDialog.vue'

export default {
  components: {
    UpdateDialog
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      companyInfo: {},
      dialogVisible: false,
      currentPid: '',
      isEdit: false,
      arrListToChild: []
    }
  },
  async created() {
    this.getDepartmentInfo()
  },
  methods: {
    async getDepartmentInfo() {
      // try {
      //   const res = await getDepartmentInfoReqest()
      //   console.log(res)
      // } catch (err) {
      //   console.log('获取组织信息接口失败：', err)
      // }
      getDepartmentInfoReqest().then(res => {
        // then有两个参数，都是函数，第一个函数是 请求成功后执行，第二个函数是请求失败后执行
        console.log('请求成功：', res)
        // this.arrListToChild = res.data.depts.map(item => ({name: xxx}))
        this.arrListToChild = res.data.depts.map(item => {
          return {
            id: item.id,
            pid: item.pid,
            name: item.name,
            code: item.code
          }
        })
        this.companyInfo = res.data.depts.shift()
        this.data = transformListToTree2(res.data.depts, '')
      }, err => {
        console.log('请求失败：', err)
      })
    },
    handleNodeClick(data) {
      // console.log(data)
    },
    // 部门新增
    addDepartment(param) {
      this.isEdit = false
      if (param) {
        this.currentPid = param.id
      } else {
        this.currentPid = ''
      }
      this.dialogVisible = true
    },
    // 部门编辑的方法
    editDepartment(param) {
      this.isEdit = true
      this.currentPid = param.id
      this.dialogVisible = true

      // this.$nextTick(() => {
      //   console.log(this.$refs.dialogRef)
      //   this.$refs.dialogRef.getDeparmentById()
      // })
    },
    updateSuccess() {
      // 创建成功以后，关闭弹窗，是由子组件触发的这个函数
      this.dialogVisible = false
      // 页面上的树形结构数据，是发请求获取的，我们只需在发一遍请求即可
      // SPA 单页面应用程序
      this.getDepartmentInfo()
    },
    async deleteDeparmentById(id) {
      await deleteDeparmentByIdRequest(id)
      this.getDepartmentInfo()
    },
    deleteDepBtn(params) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteDeparmentById(params.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style lang="scss">
.app-container {
  .company {
    display: flex;
    width: 100%;
    .c-left {
      // 项目
      flex: 1 1 80%;
      padding: 5px 10px;
      // background-color: lightblue;
    }
    .c-right {
      flex: 1 1 20%;
      padding: 5px 10px;
      // background-color: lightblue;
      display: flex;
      .cr-left {
        flex: 1 1 50%;
        // background-color: lightsalmon;
      }
      .cr-right {
        flex: 1 1 50%;
        // background-color: lightgreen;
      }
    }
  }
}
</style>
